<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>解构赋值</title>
</head>
<body>
    <h1>解构赋值</h1>

    <script>
        // 数组解构
        // bad
        const arr = [1, 2, 3];
        const first = arr[0];
        const second = arr[1];

        // good
        const [first, second] = arr;

        // 对象解构
        // bad
        const user = { firstName: '张', lastName: '三' };
        const firstName = user.firstName;
        const lastName = user.lastName;

        // good
        const { firstName, lastName } = user;

        // 函数参数的解构
        // bad
        function getFullName(user) {
            const firstName = user.firstName;
            const lastName = user.lastName;
            return `${firstName} ${lastName}`;
        }

        // good
        function getFullName({ firstName, lastName }) {
            return `${firstName} ${lastName}`;
        }

        // 实际应用示例
        // React组件props解构
        function UserProfile({ name, age, avatar, onUpdate }) {
            return `
                <div>
                    <img src="${avatar}" alt="${name}" />
                    <h2>${name}</h2>
                    <p>年龄：${age}</p>
                    <button onclick="${onUpdate}">更新</button>
                </div>
            `;
        }

        // API响应解构
        async function fetchUserData() {
            const response = await fetch('/api/user');
            const { id, name, email, settings: { theme, language } } = await response.json();
            
            console.log(`
                用户ID: ${id}
                姓名: ${name}
                邮箱: ${email}
                主题: ${theme}
                语言: ${language}
            `);
        }

        // 配置对象解构
        const config = {
            server: {
                host: 'localhost',
                port: 3000
            },
            database: {
                url: 'mongodb://localhost:27017',
                name: 'myapp'
            }
        };

        const { 
            server: { host, port },
            database: { url: dbUrl, name: dbName }
        } = config;
    </script>
</body>
</html> 